package com.wx.task;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.http.client.ClientProtocolException;
import org.json.simple.JSONValue;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.wx.config.SystemProps;
import com.wx.kit.HttpKit;
import com.wx.model.wxDb.BaseParameter;
import com.wx.repository.wxRepository.BaseParameterRepository;

@Component
public class WxBaseParameter {

	@Resource
	private BaseParameterRepository baseParameterRepository;

	@Scheduled(cron = "0 0 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 * * ?")
	// @Scheduled(cron = "0 13 10 ? * *")
	public void getAccessToken() {

		try {
			String response = HttpKit.getResponse(HttpKit.httpRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + SystemProps.appID + "&secret=" + SystemProps.appsecret));
			@SuppressWarnings("unchecked")
			Map<String, Object> responseMap = (Map<String, Object>) JSONValue.parse(response);
			String accessToken = responseMap.get("access_token").toString();
			List<BaseParameter> baseParameterArr = (List<BaseParameter>) this.baseParameterRepository.findAll();
			BaseParameter baseParameter = baseParameterArr.get(0);
			baseParameter.setUpdateTime(new Date());
			baseParameter.setAccessToken(accessToken);
			this.baseParameterRepository.save(baseParameterArr.get(0));
			System.out.println("获取access_token");
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
